#!/usr/bin/env python
# coding: utf-8


import sys

reload(sys)
sys.setdefaultencoding('utf-8')
from wxbot import *


class MyWXBot(WXBot):
    def handle_msg_all(self, msg, r):
        slog = logging.getLogger('statistics')
        # 添加好友
        if msg['msg_type_id'] == 4 and msg['content']['type'] == 12 and u'添加到通讯录' in msg['content']['data']:
            try:
                contact = msg['r']['ModContactList'][0]
                slog.debug(str(json.dumps(contact)))
            except:
                traceback.print_exc()
        elif msg['msg_type_id'] == 99 and msg['content']['type'] == 12 and u'添加到通讯录' in msg['content']['data']:
            try:
                contact = msg['r']['ModContactList'][0]
                slog.debug(str(json.dumps(contact)))
            except:
                traceback.print_exc()
        elif msg['msg_type_id'] == 99 and msg['content']['type'] == 0:
            content = msg['content']['data']
            if content == 'test':
                self.send_msg_by_uid("ok", msg['user']['id'])
        elif msg['msg_type_id'] == 4 and msg['content']['type'] == 0:
            content = msg['content']['data']
            if content == 'test':
                self.send_msg_by_uid("ok", msg['user']['id'])


def main():
    bot = MyWXBot()
    bot.DEBUG = False
    bot.conf['qr'] = 'png'
    bot.is_big_contact = True  # 如果确定通讯录过大，无法获取，可以直接配置，跳过检查。假如不是过大的话，这个方法可能无法获取所有的联系人
    # 判断参数 传入 机器人名字和配置文件
    if (len(sys.argv) < 2):
        print 'please input bot name,like python newbot.py hbot1 hbot1.conf'
        sys.exit()
    else:
        bot.temp_pwd_name = sys.argv[1]
        bot.temp_pwd = cur_file_dir() + '/temp/' + bot.temp_pwd_name
        config_pwd = cur_file_dir() + '/config/' + bot.temp_pwd_name

        if os.path.exists(bot.temp_pwd) == False:
            os.makedirs(bot.temp_pwd)

        if os.path.exists(config_pwd) == False:
            os.makedirs(config_pwd)
            f = open(config_pwd + "/config.conf", "w")
            f.close()

        bot.data_dir = cur_file_dir() + "/config/" + bot.temp_pwd_name
        bot.config_file = bot.data_dir + "/config.conf"

        if os.path.exists(bot.temp_pwd) == False:
            print 'config dir dont exists'

        if (os.path.exists(bot.config_file) == False):
            print 'config file [' + bot.config_file + '] dont exists;please check it in dir [' + bot.data_dir + ']'
            sys.exit()
    bot.loggingConfig()
    bot.run()


if __name__ == '__main__':
    main()
